<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="物料大类" v-if="permissionStore.hasPermisson('wlxl.cx')">
              <a-select popup-container="html" class="bacClass" v-model="objectOP.bigClassName1" @change="bigChange(1)"
                        :filter-option="false" allow-search allow-clear @focus="WLfocusSel('', 1)"
                        @search="WLfocusSel($event, 1)" style="width:150px">
                <a-option v-for="item in objectOP.bigName1" :value="item.id">
                  {{ item.bigClassName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="物料中类" v-if="permissionStore.hasPermisson('wlxl.cx')">
              <a-select popup-container="html" class="bacClass" :disabled="!objectOP.bigClassName1"
                        v-model="objectOP.bigClassName2"
                        @change="bigChange(2)" :filter-option="false" allow-search allow-clear
                        @focus="WLfocusSel('', 2)" @search="WLfocusSel($event, 2)" style="width:150px">
                <a-option v-for="item in objectOP.bigName2" :value="item.id">
                  {{ item.middleClassName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="物料小类" v-if="permissionStore.hasPermisson('wlxl.cx')">
              <!-- <a-input allow-clear class="bacClass" placeholder="" v-model="pageData.dropDownData"
                  @press-enter="huiche" /> -->
              <a-select popup-container="html" class="bacClass" :disabled="!objectOP.bigClassName2"
                        v-model="objectOP.bigClassName3"
                        @change="bigChange(3)" :filter-option="false" allow-search allow-clear
                        @focus="WLfocusSel('', 3)" @search="WLfocusSel($event, 3)" style="width:150px">
                <a-option v-for="item in objectOP.bigName3" :value="item.id">
                  {{ item.subClassName }}
                </a-option>
              </a-select>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar :items="pageData.btnList" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                   @export="exports" @import="importHandler" @excel="downloadHandler"></Toolbar>
        </div>

      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <!-- '导出', '导入' -->
        <!-- <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler"
            @export="exports" @import="importHandler" @excel="downloadHandler"></Toolbar> -->
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:100%;width: 100%;z-index:999 ;">
        <!--                <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"-->
        <!--                    @grid-ready="gridReady" style="height:100%" :defaultColDef="defaultColDef" class='ag-theme-alpine'-->
        <!--                    :rowData="table.dataList" :columnDefs="tc" :localeText="localeText1" @columnResized="onColumnResized"-->
        <!--                    @columnMoved="onColumnMoved"></AgGridVuesCopys>-->
        <div style="width: 100%; height: 100%">
          <encapsulation-agrid ref="table1Ref" :configaggrid="configTable1"></encapsulation-agrid>
        </div>
      </a-spin>
    </template>
    <a-drawer style="z-index:999" ok-text='保存' cancel-text='关闭' :mask-closable="false"
              :drawer-style="{ 'zIndex': 9999 }" :width="400" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
              @cancel="pageData.showAdd = false" :ok-loading="pageData.pageLoading">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item label="物料大类" field="bigClassId" :rules="[{ required: true, message: '物料大类必选' }]"
                       label-col-flex="80px" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html" class="bacClass" :style="{ width: '320px' }" :loading="loading"
                      @search="handleSearchs"
                      v-model="dataForm.bigClassId" :filter-option="false" allow-search allow-clear @focus="focusSels"
                      @change="cahngesBass">
              <a-option v-for="item in pageData.nameLists" :value="item.id">{{
                  item.bigClassName
                }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="物料中类" field="middleClassId"
                       :rules="[{ required: true, message: '物料中类名称必填' },]"
                       label-col-flex="80px" :validate-trigger="['change', 'blur']">
            <a-select popup-container="html" :disabled="!dataForm.bigClassId" class="bacClass" @click="DaLeiLists"
                      v-model="dataForm.middleClassId" allow-search allow-clear>
              <a-option v-for="item in DaLeiList" :value="item.id">{{
                  item.middleClassName
                }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item label="物料小类" field="subClassName" :rules="[{ required: true, message: '名称必填' }]"
                       label-col-flex="80px" :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" v-model="dataForm.subClassName"/>
          </a-form-item>
          <a-form-item label="编号" field="subClassCode"
                       :rules="[{ validator: isChiese }, { required: true, message: '编码必填' }]" label-col-flex="80px"
                       :validate-trigger="['change', 'blur']">
            <a-input class="bacClass" v-model="dataForm.subClassCode" @blur="inputBlur"/>
          </a-form-item>
          <a-form-item label="备注" field="remark" label-col-flex="80px">
            <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear
                        show-word-limit/>
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script setup lang="ts">
import {post} from '@/api/http'
import {usePagination, useRowKey, useRowSelection, useTable, useTableColumn} from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import {onMounted, reactive, ref} from 'vue'
import {Message, Modal} from '@arco-design/web-vue';
import {FormInstance} from '@arco-design/web-vue/es/form';
import {baseURL} from '@/api/axios.config'
import axios from "axios";
import usePermission from '@/store/modules/permission'

import {localeText} from '@/api/aggridZw'
import {pagingList} from '@/api/paging'
import {simplifyMessages} from '@/api/messageSimplification'
import {saveOrUpdateGridState as saveOrUpdateGridState01} from '@/hooks/useGridState'
import buttionRender from "@/components/aggridCellRenDerer/buttionRender.vue";

interface ProcurementType {
  "id": any
  "bigClassName": any
  "subClassCode": any
  "subClassName": any
  "remark": any
  "encoding": any
}

const objectOP = reactive<any>({
  bigClassName1: '',
  bigClassName2: '',
  bigClassName3: '',
  bigName1: [],
  bigName2: [],
  bigName3: []
})
const pageData: any = reactive({
  nameList: [],
  nameLists: [],
  showAdd: false,
  sideTitle: '新增物料小类',
  dropDownData: "",
  dropDownData2: "",
  dropDownData3: "",
  pageLoading: false,
  rHeight: "",
  btnList: [],
  isEdit: false
});
//设置权限
// ['查询', '新增', '删除', '导出', '导入']
const permissionStore = usePermission()

if (permissionStore.hasPermisson('wlxl.cx')) {

  pageData.btnList.push("查询")
}
if (permissionStore.hasPermisson('wlxl.xz')) {
  pageData.btnList.push("新增")
}
if (permissionStore.hasPermisson('wlxl.sc')) {
  pageData.btnList.push("删除")
}
// pageData.btnList.push("导入")
if (permissionStore.hasPermisson('wlxl.xg')) {
  pageData.isEdit = true
}
const table1Ref = ref<any>(null)
const tableColumns = [
  {
    field: '',
    headerCheckboxSelection: true,
    checkboxSelection: true,
    width: 50,
    showDisabledCheckboxes: false,
    pinned: 'left',
  },
  {
    headerName: "大类编号",
    field: "bigClassCode",
    width: 150
  },
  {
    headerName: "物料大类",
    field: "bigClassName",
    width: 150
  },
  {
    headerName: "中类编号",
    field: "middleClassCode",
    width: 150
  },
  {
    headerName: "物料中类",
    field: "middleClassName",
    width: 150
  },
  {
    headerName: "小类编号",
    field: "subClassCode",
    width: 150
  },
  {
    headerName: "物料小类",
    field: "subClassName",
    width: 150
  },
  {
    headerName: "备注",
    field: "remark",
    width: 150
  },
  {
    headerName: "创建人",
    field: "createName",
    width: 150
  },
  {
    headerName: "创建时间",
    field: "createTime",
    width: 200
  },
  {
    headerName: "最后修改人",
    field: "updateName",
    width: 150
  },
  {
    headerName: "最后修改时间",
    field: "updateTime",
    width: 200
  },
  {
    headerName: '操作',
    field: 'action',
    slotName: 'action',
    width: 150,
    pinned: 'right',
    cellRenderer: buttionRender,
    cellRendererParams: {
      buttonList: [
        {
          type: 'primary',
          text: '修改',
          typeName: 'el-button',
          show: pageData.isEdit,
          Callback: (data: any) => {
            editHandler(data)
          },
        },
      ],
      eltagSize: 0,
    },
  }
]
let configTable1 = {
  url: 'purchase/MaterialSubClass/getPage', //接口路径
  queryData: {
    deleteState: 0,
    subClassName: pageData.dropDownData,
    bigClassName: pageData.dropDownData3,
    middleClassName: pageData.dropDownData2,
  },
  paginationShow: true, //分页是否显示
  invokeiIterface: true, //是否调用接
  rowMultiSelectWithClick: true, //点击行是否多选
  column: tableColumns,
  fileName: 'SmallClass01'
}

const total = ref(0);
const page = ref(1);
const size = ref(10);

function PageSize(val: any) {
  pagination.page = val
  doRefresh();
}

function change1(val: any) {
  pagination.pageSize = val
  doRefresh();
}

function doRefresh() {
  table1Ref.value.setQuery({
    deleteState: 0,
    subClassName: pageData.dropDownData,
    bigClassName: pageData.dropDownData3,
    middleClassName: pageData.dropDownData2,
  })
}

const {selectedRowKeys, onSelectionChange} = useRowSelection();
const pagination = usePagination(doRefresh);
const table = useTable();
const rowKey = useRowKey("id");
//下拉框得到焦点
const focusSel = () => {
  selCxAll({subClassName: ''})
}
//下拉数据
const options = ref<any>(pageData.nameList);
const loading = ref(false);
const handleSearch = (value: any) => {
  if (value) {
    const ob = {subClassName: value}
    loading.value = true;
    selCxAll(ob);
    options.value = pageData.nameList;
    loading.value = false;
  } else {
    options.value = []
  }
};

//下拉框查询
function selCxAll(val: any) {
  post({
    url: "purchase/MaterialSubClass/getFieldValue",
    data: val
  }).then(({data, code}: any) => {
    if (code === 200) {
      console.log(data);
      // (data as string[]).splice(0, 0, "全部");
      pageData.nameList = data;

    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

onMounted(() => {
  emitter.on("SmallClass", () => {
    doRefresh();
  });
  pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
  //表格的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight - 200;

    console.log(pageData.rHeight);

  }
  window.addEventListener('resize', () => {
    pageData.rHeight = document.getElementById("BaseInfoSetting")?.clientHeight

    //表格的高
    if (pageData.rHeight !== undefined) {
      pageData.rHeight = pageData.rHeight - 200;
    }

  })
});
//查询
const selectHandler = () => {
  pagination.page = 1
  doRefresh();
}
const queryData = reactive({

  clothType: ""
});
const addHandler = () => {
  //清空数据
  for (const key in dataForm) {
    if (key == "id") {
      dataForm.id = null;
    } else {
      dataForm[key] = '';
    }
  }
  pageData.showAdd = true
  pageData.sideTitle = '新增物料小类'

}

const dataForm = reactive<ProcurementType>({
  "id": null,
  "bigClassId": '',
  "middleClassId": '',
  "subClassName": '',
  "remark": "",
  "encoding": "",
})

// 表格准备事件
const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
  colState.value = params.columnApi
}

const formRef = ref<FormInstance>()
const sideOk = () => {
  formRef.value?.validate().then((err) => {
    if (!err) {
      if (pageData.sideTitle === "新增物料小类") {
        delete dataForm.id
        pageData.pageLoading = true
        post({
          url: "purchase/MaterialSubClass/insert",
          data: [dataForm],
        }).then((res: any) => {
          if (res.code === 200) {
            formRef.value?.resetFields();
            pageData.showAdd = false;
            doRefresh();
            Message.success({
              content: "新增成功",
              duration: 5000,
            });
          } else {
            Message.error({
              content: res.message,
              duration: 5000,
            });
          }
        }).then(() => {
          pageData.pageLoading = false
        })
      } else {
        post({
          url: "purchase/MaterialSubClass/update",
          data: [dataForm],
        }).then((res: any) => {
          if (res.code === 200) {
            formRef.value?.resetFields();
            pageData.showAdd = false;
            doRefresh();
            //清空数据
            for (const key in dataForm) {
              if (key == "id") {
                dataForm.id = null;
              } else {
                dataForm[key] = '';
              }
            }
            Message.success({
              content: "修改成功",
              duration: 5000,
            });
          } else {
            Message.error({
              content: simplifyMessages(res.message),
              duration: 5000,
            });
          }
        });
      }
    }
  });
}
const deleteHandler = () => {
  if (table1Ref.value.getSelectedRows().length === 0) {
    Message.error('请先勾选');
    return
  }
  Modal.confirm({
    title: '系统提示',
    content: '确认删除选中的数据?',
    onOk() {
      post({
        url: 'purchase/MaterialSubClass/delete',
        // data: selectedRowKeys.value
        data: table1Ref.value.getSelectedRows().map((o: any) => {
          return o.id
        })
      }).then(({code, data, message}: any) => {
        if (code === 200) {
          Message.success({
            content: '删除成功',
            duration: 5000
          })
          page.value = 1
          doRefresh()
        } else {
          Message.error({
            content: simplifyMessages(message),
            duration: 5000
          })
        }

      })
    }
  })
}
const editHandler = (record: ProcurementType) => {
  selCxAlls({})
  dataForm.id = Number(record.id);
  dataForm.bigClassId = record.bigClassId;
  DaLeiLists()
  dataForm.middleClassId = record.middleClassId;
  dataForm.subClassName = record.subClassName;
  dataForm.subClassCode = record.subClassCode;
  dataForm.remark = record.remark;
  pageData.sideTitle = '修改物料小类'
  pageData.showAdd = true
};
//判断是否填写了中文
const isChiese = (value: string, cb: Function) => {
  return new Promise<void>(resolve => {
    if (window.encodeURI(value).indexOf('%') !== -1) {
      cb('填写的值不能包含中文！')
    }
    resolve()
  })

}
//input离开焦点 将小写转大写
const inputBlur = () => {
  // dataForm.subClassCode = dataForm.subClassCode.toUpperCase();
  dataForm.encoding = dataForm.encoding.toUpperCase();
}
//导出
const exports = () => {
  // if (selectedRowKeys.value.length === 0) {
  //     Message.error('请先勾选')
  //     return
  // }
  if (gridOption.value.getSelectedRows() === 0) {
    Message.error('请先勾选');
    return
  } else {
    //将表头拼接出来
    let head = "<th>类型编号</th><th>类型名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
    //拿到当前表格数据与勾选的行做筛选

    let nowRow = table.dataList.filter(function (o) {
      return selectedRowKeys.value.indexOf(o["id"]) !== -1;
    })
    let body = "";
    nowRow.forEach(function (o) {
      body += "<tr><td>" + o["productTypeCode"] + "</td>";
      body += "<td>" + o["productTypeName"] + "</td>";
      body += "<td>" + o["remark"] + "</td>";
      body += "<td>" + o["createName"] + "</td>";
      body += "<td>" + o["createTime"] + "</td>";
      body += "<td>" + o["updateName"] + "</td>";
      body += "<td>" + o["updateTime"] + "</td>";
      body += "</tr>";
    })
    tableToXlsx(head, '产品类型', body)
    console.log(table)
  }
}

function tableToXlsx(head: any, filename: any, body: any) {
  const uri = 'data:application/vnd.ms-excel;base64,',
      template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

  const a = document.createElement('a');
  a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
  a.download = filename;
  a.click();
  document.removeChild(a);
}

//模板下载
const downloadHandler = () => {
  window.open(baseURL + 'excel')
}
//导入
const importHandler = () => {

  const inputEle: HTMLInputElement = document.createElement('input')
  inputEle.type = 'file'
  inputEle.id = 'fileUploadExcel'
  inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
  inputEle.addEventListener('change', (e) => {
    const formData = new FormData()
    if (inputEle.files !== null) {
      formData.append('file', inputEle.files[0] || '')
    } else {
      Message.warning('未选择文件！');
      return
    }
    pageData.pageLoading = true
    axios.post(baseURL + '/purchase/MaterialSubClass/importModelData', formData, {
      headers: {
        "Content-Type": 'multipart/form-data',
        "token": sessionStorage.getItem('USER-TOKEN-KEY')
      },
    }).then((result) => {
      if (result.data['code'] === 200) {
        Message.success('导入成功')
      } else {
        Message.error(result.data.message)
      }

    }).finally(() => {
      pageData.pageLoading = false
      doRefresh()
    })
  })
  inputEle.click()
}

//下拉框得到焦点
const focusSels = () => {
  selCxAlls({bigClassName: ''})
}
//下拉数据
const optionss = ref<any>(pageData.nameLists);
const loadings = ref(false);
const handleSearchs = (value: any) => {
  if (value) {
    const ob = {bigClassName: value}
    loadings.value = true;
    window.setTimeout(() => {
      selCxAlls(ob);
      optionss.value = pageData.nameLists;
      loadings.value = false;
    }, 200)
  } else {
    optionss.value = []
  }
};

//下拉框查询
function selCxAlls(val: any) {
  post({
    url: "purchase/MaterialBigClass/getList",
    data: {}
  }).then(({data, code}: any) => {
    if (code === 200) {
      console.log(data);
      // (data as string[]).splice(0, 0, "全部");
      pageData.nameLists = data;

    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

const headerShow = ref<boolean>(true)
const handleChange = (_data: any) => {
  table.handleSuccess(_data);
}
const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
  // flex: 1
}
const localeText1: any = ref(localeText)
const huiche = () => {
  selectHandler();
}
const pagingList1: any = ref(pagingList)
const isChiese1 = (value: string, cb: Function) => {
  return new Promise<void>((resolve) => {
    var reg = /^[\u4E00-\u9FA5]+$/;
    if (!reg.test(value)) {
      cb('请填写中文！')
    }
    resolve()
  })
}

const DaLeiList: any = ref()

const DaLeiLists = () => {
  post({
    url: '/purchase/MaterialMiddleClass/getList',
    data: {
      bigClassId: dataForm.bigClassId
    }
  }).then(({code, data}) => {
    DaLeiList.value = data
  })
}

const cahngesBass = () => {
  dataForm.middleClassId = ''
}
const bigChange = (val: any) => {
  if (val === 1) {
    pageData.dropDownData3 = ''
    objectOP.bigName2 = []
    objectOP.bigClassName2 = ''
    objectOP.bigName3 = []
    objectOP.bigClassName3 = ''
    objectOP.bigName1.forEach((item: any) => {
      if (item.id == objectOP.bigClassName1) {
        pageData.dropDownData3 = item.bigClassName
      }
    })
  } else if (val === 2) {
    pageData.dropDownData2 = ''
    objectOP.bigName3 = []
    objectOP.bigClassName3 = ''
    objectOP.bigName2.forEach((item: any) => {
      if (item.id == objectOP.bigClassName2) {
        pageData.dropDownData2 = item.middleClassName
      }
    })
  } else if (val === 3) {
    pageData.dropDownData = ''
    objectOP.bigName3.forEach((item: any) => {
      if (item.id == objectOP.bigClassName3) {
        pageData.dropDownData = item.subClassName
      }
    })
  }
}
//下拉框   物料大类  
const WLfocusSel = (item: any, val: any) => {
  if (val === 1) {
    post({
      url: 'purchase/MaterialBigClass/getFieldValue',
      data: {bigClassName: item},
    }).then(({data, code}: any) => {
      if (code === 200) {
        objectOP.bigName1 = data
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    })
  } else if (val === 2) {
    post({
      url: 'purchase/MaterialMiddleClass/getFieldValue',
      // data: { bigClassId: objectOP.bigClassName1 },
      data: {"middleClassName": item, filterMap: {"bigClassId": objectOP.bigClassName1}}
    }).then(({data, code}: any) => {
      if (code === 200) {
        objectOP.bigName2 = data
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    })
  } else if (val === 3) {
    post({
      url: 'purchase/MaterialSubClass/getFieldValueFilter',
      // data: { middleClassId: objectOP.bigClassName2 },
      data: {"subClassName": item, filterMap: {"middleClassId": objectOP.bigClassName2}}
    }).then(({data, code}: any) => {
      if (code === 200) {
        objectOP.bigName3 = data
      } else {
        Message.error({
          content: '查询失败！',
          duration: 5000,
        })
      }
    })
  }
}
</script>

<style lang="less"></style>